package com.huluobo.jetpackdemo

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider

class ADActivity : AppCompatActivity() {
    private lateinit var adViewModel: ADViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ad)

        val time = findViewById<TextView>(R.id.time)
        val cancel = findViewById<Button>(R.id.cancel)

        adViewModel = ViewModelProvider(this)[ADViewModel::class.java]

//        //如果发生了反转,则bundle不为空,就可以取出时间
//        if (savedInstanceState != null) {
//            timing = savedInstanceState.getLong("time")
//        }

        val adManager = AdManager(adViewModel)
        //观察模式三要素,被观察者是当前的activity,由于继承关系,已经实现了LifeCycleOwner的接口(宿主接口,被观察者),所以不需要再次实现
        //通过  lifecycle.addObserver(adManager) 产生订阅关系
        //观察者是adManager,实现了LifecycleObserver
        lifecycle.addObserver(adManager)
        adViewModel.timingResult.observe(this) {
            adViewModel.timing = it
            time.text = "广告剩余时间;${(it / 1000).toInt()}秒"
            if (it / 1000 <= 1) {
                val intent = Intent(this@ADActivity, MainActivity::class.java)
                this@ADActivity.startActivity(intent)
                this@ADActivity.finish()
            }
        }

//        adManager.adListener = object : AdManager.ADListener {
//            override fun onTiming(second: Int) {
//                time.text = "广告剩余时间:${second}秒"
//                adViewModel.timing = second.toLong() * 1000
//            }
//
//            override fun onFinish() {
//                val intent = Intent(this@ADActivity, MainActivity::class.java)
//                this@ADActivity.startActivity(intent)
//                this@ADActivity.finish()
//            }
//        }

        cancel.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
    }

//    //当生命周期发生反转的时候,保存当前时间
//    override fun onSaveInstanceState(outState: Bundle) {
//        super.onSaveInstanceState(outState)
//        outState.putLong("time", timing)
//    }
}